<script setup lang="ts">
import dayjs from 'dayjs';
import { getUsers } from '@/api';
import { GetUserReturn } from '@/interfaces/aboutApi';
import { commonEnums } from '@/enums';
import { UserFilled } from '@element-plus/icons-vue';
import { VxePagerEvents, VxeTablePropTypes } from 'vxe-table';
import jsonToExcel from '@/utils/exportToExcel';

interface ItableData {
  apiResult: GetUserReturn[];
  tableData: GetUserReturn[];
}
interface Istate extends ItableData {
  loading: boolean;
  pageNum: number;
  pageSize: number;
  total: number;
}
const state: Istate = reactive({
  apiResult: [],
  loading: true,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

function init() {
  state.loading = true;
  getUsers()
    .then((res) => {
      state.loading = false;
      state.apiResult = res.result;
      state.total = res.result.length;
      state.tableData = handlePagination(res.result);
    })
    .catch((err: any) => err)
    .finally(() => (state.loading = false));
}

const seqConfig = ref({
  seqMethod({ rowIndex }) {
    return (state.pageNum - 1) * 10 + rowIndex + 1;
  },
} as VxeTablePropTypes.SeqConfig);

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  state.pageNum = currentPage;
  state.pageSize = pageSize;
  state.tableData = handlePagination(state.apiResult);
};

// 处理分页
const handlePagination = (apiResult: GetUserReturn[]) => {
  return apiResult.filter((item: GetUserReturn, index: number) => {
    let idx = index - (state.pageNum - 1) * state.pageSize;
    return idx < state.pageSize && idx >= 0;
  });
};

const tableRef = ref<HTMLTableElement | null>(null);
const handleExport = () => {
  let arr = state.apiResult.map((item) => {
    let roles = item.roles.map((el) => {
      if (el === 'admin') return '管理员';
      else return '用户';
    });
    return {
      _id: item._id,
      roles: roles.join(),
      username: item.username,
      avatar: item.avatar_url || '暂无头像',
      phoneNumber: item.phoneNumber || '未知',
      sex: item.sex,
      creatTime: dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss'),
      updateTime: dayjs(item.update_time).format('YYYY-MM-DD HH:mm:ss'),
    };
  });

  let options = {
    arr,
    header: {
      _id: '唯一id',
      roles: '权限',
      username: '用户名',
      avatar: '头像',
      phoneNumber: '手机号',
      sex: '性别',
      creatTime: '创建时间',
      updateTime: '更新时间',
    },
    fileName: `${dayjs().format('YYYY-MM-DD')}_vue_admin_z后台用户`,
  };

  jsonToExcel(options);
};

onMounted(() => {
  init();
});
</script>

<template>
  <div class="p-4 box-border">
    <el-card class="mb-5">
      <el-button type="success" @click="handleExport">导出为excel</el-button>
    </el-card>
    <el-card shadow="hover">
      <vxe-table
        ref="tableRef"
        border
        :seq-config="seqConfig"
        max-height="518"
        :loading="state.loading"
        show-overflow="tooltip"
        :column-config="{ resizable: true }"
        :row-config="{ isHover: true, height: 120 }"
        :data="state.tableData"
      >
        <vxe-column type="seq" title="序号" width="60" align="center"></vxe-column>
        <vxe-column field="_id" title="_id" width="140"></vxe-column>
        <vxe-column field="roles" title="权限" width="140">
          <template #default="{ row }">
            <el-tag v-for="item in row.roles" :key="item" effect="dark" :type="item === 'admin' ? 'danger' : ''" class="mr-1 mb-1">{{
              item === 'admin' ? '管理员' : '用户'
            }}</el-tag>
          </template>
        </vxe-column>
        <vxe-column field="username" title="用户名"></vxe-column>
        <vxe-column field="avatar_url" title="头像" align="center">
          <template #default="{ row }">
            <el-avatar v-if="row.avatar_url" :size="28" :src="row.avatar_url" />
            <el-avatar v-else :size="28" :icon="UserFilled" />
          </template>
        </vxe-column>
        <vxe-column field="phoneNumber" title="手机号" align="center">
          <template #default="{ row }">
            <span>{{ row.phoneNumber || '未知' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="sex" title="性别" align="center">
          <template #default="{ row }">
            <el-tag :type="row.sex === commonEnums.FEMALE ? 'danger' : ''">{{ row.sex }}</el-tag>
          </template>
        </vxe-column>
        <vxe-column field="create_time" title="创建时间">
          <template #default="{ row }">
            <span>{{ dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </vxe-column>
        <vxe-column field="update_time" title="更新时间">
          <template #default="{ row }">
            <span>{{ dayjs(row.update_time).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </vxe-column>
        <vxe-column title="图片">
          <template #default>
            <img src="https://pic2.zhimg.com/50/v2-f7031359103859e1ed38559715ef5f3f_hd.gif" style="width: 100px" />
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-pager
        size="small"
        background
        :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
        v-model:current-page="state.pageNum"
        v-model:page-size="state.pageSize"
        :total="state.total"
        @page-change="handlePageChange"
      >
      </vxe-pager>
    </el-card>
  </div>
</template>

<style scoped lang="scss"></style>
